<template>
  <div class="user-list">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form
          :inline="true"
          ref="form"
          :model="form"
          class="demo-form-inline"
        >
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="注册时间" prop="time">
            <el-date-picker
              v-model="form.time"
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-row>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-row>
        </el-form>
      </div>
      <el-table :data="users" v-loading="isLoading" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="120">
        </el-table-column>
        <el-table-column prop="" label="头像" width="60">
          <template slot-scope="scope">
            <!-- || require('@/assets/headImg.jpg') -->
            <el-avatar size="small" :src="scope.row.portrait"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="用户名"> </el-table-column>
        <el-table-column prop="phone" label="手机号"> </el-table-column>
        <el-table-column prop="createTime" label="注册时间"> </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-button
              :type="scope.row.status === 'DISABLE' ? 'danger' : 'success'"
              size="small"
              circle
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleForbidUser(scope.row)"
              v-if="scope.row.status !== 'DISABLE'"
              >禁用</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="handleSelectRole(scope.row)"
              >分配角色</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :disabled="isLoading"
        :current-page.sync="form.currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="form.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
      <el-dialog title="分配角色" :visible.sync="dialogVisible" width="500px">
        <el-select v-model="roleIdList" multiple placeholder="请选择">
          <el-option
            v-for="item in roles"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleAllocRole">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getUsers, setForbidUser } from '@/services/user'
import { getTime } from '@/utils/time'
import { Form } from 'element-ui'
import { getAllRoles, allocateUserRoles, getUserRoles } from '@/services/role'

export default Vue.extend({
  name: 'UserList',
  created () {
    this.loadUserList()
  },
  data () {
    return {
      form: {
        phone: '',
        time: [],
        currentPage: 1,
        pageSize: 10,
        userId: null,
        startCreateTime: '',
        endCreateTime: ''
      },
      currentUser: null, // 分配角色的当前用户
      totalCount: 0,
      isLoading: false,
      users: [],
      dialogVisible: false,
      roles: [],
      roleIdList: []
    }
  },
  methods: {
    onSubmit () {
      this.form.currentPage = 1
      if (this.form.time.length === 2) {
        this.form.startCreateTime = (this.form.time[0] as Date).toISOString()
        this.form.endCreateTime = (this.form.time[1] as Date).toISOString()
      }
      this.loadUserList()
    },
    onReset () {
      (this.$refs.form as Form).resetFields()
      this.form.startCreateTime = ''
      this.form.endCreateTime = ''
    },
    async loadUserList () {
      this.isLoading = true
      const { data } = await getUsers(this.form)
      this.users = data.data.records.map((item: any) => {
        item.createTime = getTime(item.createTime)
        return item
      })
      this.totalCount = data.data.total
      this.isLoading = false
    },
    handleForbidUser (user: any) {
      this.$confirm('是否封禁用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 禁用用户
          await setForbidUser(user.id)
          this.$message.success('封禁用户成功')
          this.loadUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async handleSelectRole (user: any) {
      this.currentUser = user
      // 加载角色列表
      const { data } = await getAllRoles()
      this.roles = data.data
      // 获取用户角色
      const { data: userRoles } = await getUserRoles(user.id)
      this.roleIdList = userRoles.data.map((i: any) => i.id)
      // 展示对话框
      this.dialogVisible = true
    },
    handleSizeChange (val: number) {
      // 修改每页大小
      this.form.pageSize = val
      // 每页大小改变重新查询第一页数据
      this.form.currentPage = 1
      // 重新请求数据
      this.loadUserList()
    },
    handleCurrentChange (val: number) {
      // 修改要查询的页码
      this.form.currentPage = val
      // 重新请求数据
      this.loadUserList()
    },
    async handleAllocRole () {
      await allocateUserRoles({
        userId: (this.currentUser as any).id,
        roleIdList: this.roleIdList
      })
      this.$message.success('分配成功')
      this.dialogVisible = false
    }
  }
})
</script>

<style lang="scss" scoped></style>
